<template>
	<view>
		<view class="wrap mb64" >
			<u-sticky bgColor="#ffffff">
				<view class="u-tabs-box">
					<u-tabs lineColor="#e64340" :list="list" :current="current" @change="change"></u-tabs>
				</view>
			</u-sticky>
			<page-box-empty v-if="!orderList || orderList.length == 0" title="您还没有相关的订单" sub-title="快去下一单吧～" :show-btn="false" />
			<view v-else class="page-box">
				<view class="order" v-for="(item, index) in orderList" :key="item.id">
					<view class="top" @click="goUrl('./detail?id=' + item.id)">
						<view class="left">
							订单号: {{ item.sn }}
						</view>
						<view class="right">{{ mapStatus.get(item.status.toString()) }}</view>
					</view>
					<view class="mt32">
						<view class="mb16 flex">发单人: {{ item.senderName }}
							<u-icon name="phone" color="#2979ff"  size="48rpx" @click="tapCall(item.senderPhone)"></u-icon>
						</view>
						<view class="mb16">地址: {{ item.receiverProvince+item.receiverCity+item.receiverRegion+item.receiverDetailAddress }}</view>
						<view class="mb16">物品: {{ item.goodsName }}</view>
						<view v-if="item.remark" class="mb16">留言: {{ item.remark }}</view>
					</view>
					<view class="total">
						<view class="price-score" style="display: inline-flex;">
							<view v-if="item.amountTotal" class="item"><text>¥</text>{{item.amountTotal}}</view>
						</view>
					</view>
					<view class="mt32">
						<u-line></u-line>
					</view>
					<view class="bottom">
						<view class="evaluate btn ml24" @click="take(item.id)" v-if="item.status == 0">接单</view>
						<view class="evaluate btn" @click="close(item.id)" v-if="item.status == 1">取消订单</view>
						<view class="evaluate btn" @click="goUrl('../order/detail?id='+item.id)" v-if="item.status > 1">查看订单</view>
					</view>
					<!-- <view v-else-if="item.status == -1" class="bottom">
						<view class="exchange btn" @click="orderDelete(item.id)">删除</view>
					</view>
					<view v-if="item.status > 0 && !item.isEnd" class="bottom">
						<view v-if="item.refundStatus == 1 || refundApplyedOrderIds.includes(item.id + '')" class="btn-box">
							<u-button type="error" plain size="small" shape="circle" text="撤销售后"
								@click="refundCancel(item)"></u-button>
						</view>
						<view v-else class="btn-group">
							<view class="btn-box">
								<u-button type="error" plain size="small" shape="circle" text="退换货" @click="refund(item)"></u-button>
							</view>
							<view v-if="!item.invoiceId && item.status >= 3" class="btn-box">
								<u-button type="success" plain size="small" shape="circle" text="申请发票" @click="invoice(item)"></u-button>
							</view>
						</view>
					</view> -->
				</view>
				
			</view>
		</view>
		<u-loadmore :status="status" loading-text="努力加载中" loadmore-text="" nomore-text=""/>
	</view>
</template>

<script>
	const PAY = require('@/common/pay.js')
	export default {
		data() {
			return {
				status: 'loadmore',
				page:1,
				orderList: [],
				refundApplyedOrderIds: undefined,
				dataList: undefined,
				mapStatus: new Map([
				  ["0","待接单"],
				  ["1","已接单"],
				  ["2","运输中"],
				  ["3","已完成"],
				]),
				list: [{
						name: '全部',
						status: ''
					},
					{
						name: '待接单',
						status: '0'
					},
					{
						name: '已接单',
						status: '1'
					},
					{
						name: '运输中',
						status: '2'
					},
					{
						name: '已完成',
						status: '3'
					},
				],
				current: 0,
			};
		},
		onLoad(e) {
			if (e.status) {
				const a = this.list.findIndex(ele => {
					return ele.status == e.status
				})
				if (a != -1) {
					this.current = a * 1
				}
			}
		},
		onShow() {
			this.refundApplyedOrderIds = uni.getStorageSync('refundApplyedOrderIds')

			this.change({
				index: this.current
			})
		},
		onReachBottom() {
			this.status = 'loading';
			this.page++
			this._getData()
		},
		onPullDownRefresh() {
			this.page = 1
			this._getData()
			uni.stopPullDownRefresh()
		},
		methods: {
			async _getData() {
				uni.showLoading({
					title: ''
				})
				
				const res = await this.$wxapi.orderPageWuliu({
					token:this.token,
					userId:getApp().globalData.userId,
					status:this.list[this.current].status,
					pageNo: this.page,
					pageSize: 10
				})
				uni.hideLoading()
				if (res.code == 0) {
					if (this.page == 1) {
						this.orderList.length = 0;
						this.orderList=this.orderList.concat(res.data.data)
					} else {
						if (res.data.data&&res.data.data.length>0) {
							this.status = 'loadmore';
							this.orderList=this.orderList.concat(res.data.data)
						} else {
							this.status = 'nomore';
							uni.showToast({
								title: '没有更多了～',
								icon: 'none'
							})
						}
					}
				}
			},
			goIndex() {
				uni.switchTab({
					url: "../home/index"
				})
			},
			// tab栏切换
			change(e) {
				this.current = e.index
				this.page = 1
				this._getData();
			},
			async close(orderId) {
				uni.showModal({
					title: '请确认',
					content: '确定要取消该订单吗？',
					success: res => {
						if (res.confirm) {
							this.goUrl("../order/deletewhy?orderId="+orderId)
						}
					}
				});
			},
			async _close(orderId, deleteWhy) {
				const res = await this.$wxapi.orderClose(this.token, orderId, deleteWhy)
				if (res.code != 0) {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
				} else {
					uni.showToast({
						title: '已取消'
					})
					this.change({
						index: this.current
					})
				}
			},
			async take(orderId) {
				this.goUrl("../order/comment?id="+orderId)
			},
			async orderDelete(orderId) {
				uni.showModal({
					title: '请确认',
					content: '确定要删除该订单吗？删除后无法恢复！',
					success: res => {
						if (res.confirm) {
							this._orderDelete(orderId)
						}
					}
				});
			},
			async _orderDelete(orderId) {
				// https://www.yuque.com/apifm/nu0f75/wh4rrs
				const res = await this.$wxapi.orderDelete(this.token, orderId)
				if (res.code != 0) {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
				} else {
					uni.showToast({
						title: '删除成功'
					})
					this.change({
						index: this.current
					})
				}
			},
			async pay(index) {
				// https://www.yuque.com/apifm/nu0f75/wrqkcb
				let res = await this.$wxapi.userAmount(this.token)
				let balance = 0
				if (res.code != 0) {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
				}
				balance = res.data.balance
				const orderInfo = this.orderList[index]
				const needPay = (orderInfo.amountReal - balance).toFixed(2)
				if (needPay <= 0) {
					// 直接调用支付接口 https://www.yuque.com/apifm/nu0f75/lwt2vi
					const res = await this.$wxapi.orderPay(this.token, orderInfo.id)
					if (res.code != 0) {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					} else {
						uni.showToast({
							title: '支付成功'
						})
						this.change({
							index: 1
						})
					}
				} else {
					// 发起在线支付
					PAY.pay('wxpay', {
						appid: getApp().globalData.wxpayOpenAppId
					}, needPay, '支付订单 ：' + orderInfo.id, '支付订单 ：' + orderInfo.id, {
						type: 0,
						id: orderInfo.id
					}, () => {
						this.change({
							index: 1
						})
					}, (err) => {
						uni.showToast({
							title: '支付失败',
							icon: 'none'
						})
					})
				}
			},
			async refund(item) {
				if(item.type == 5) {
					// 京东权益订单，判断是否可售后
					const goodsId = item.goodsList[0].goodsIdStr
					uni.setStorageSync('afsGoodsId', goodsId) // 京东权益订单，售后的商品编号
					const res = await this.$wxapi.joycityPointsCanApplyAfterSale({
						token: this.token,
						orderId: item.id,
						goodsId
					})
					if(res.code != 0) {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
						return
					}
					if(!res.data.canApply) {
						uni.showToast({
							title: res.data.cannotApplyTip,
							icon: 'none'
						})
						return
					}
					if(res.data.supportMethod == 2) {
						uni.showToast({
							title: '请联系客服进行售后:' + res.data.afsHotLine,
							icon: 'none'
						})
						return
					}
					// 可申请的售后类型保存到 storage
					uni.setStorageSync('supportAfsTypeList', res.data.supportAfsTypeList) // 支持的售后类型列表 10-退货 20-换货
				}
				uni.setStorageSync('orderType', item.type)
				uni.navigateTo({
					url: '../refund/apply?orderId=' + item.id
				})
			},
			async refundCancel(item) {
				uni.showModal({
					title: '请确认',
					content: '确定要撤销售后吗？',
					success: res => {
						if (res.confirm) {
							this._refundCancel(item)
						}
					}
				});
			},
			async _refundCancel(item) {
				// https://www.yuque.com/apifm/nu0f75/bq6e6r
				const res = await this.$wxapi.refundApplyCancel(this.token, item.id)
				if (res.code == 0) {
					uni.showToast({
						title: '已撤销',
						icon: 'none'
					})
					this._getData();
				} else {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
				}
			},
			invoice(item) {
				uni.navigateTo({
					url: '/pages/invoice/apply?orderId=' + item.id
				})
			},
			tapCall(value) {
				uni.makePhoneCall({
					phoneNumber: value
				})
			},
			goUrl(url) {
				if (url) {
					uni.navigateTo({
						url
					})
				}
			},
			async payOrder(id) {
				this._payOrder(id)
			},
			async _payOrder(id) {
				const res = await this.$wxapi.payOrder(this.token, id)
				if (res.code == 0) {
					this.goUrl("../order/paysuccess")
				} else {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
				}
			},
			async deliveryOrder(id) {
				uni.showModal({
					title: '确定要确认收货吗？',
					content: '请货到现场并检查无误后再确认收货',
					success: res => {
						if (res.confirm) {
							this._deliveryOrder(id)
						}
					}
				})
			},
			async _deliveryOrder(id) {
				const res = await this.$wxapi.deliveryOrder(this.token, id)
				if (res.code == 0) {
					this.change({
						index: this.current
					})
				} else {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
				}
			},
		}
	};
</script>

<style>
	/* #ifndef H5 */
	page {
		background-color: #f2f2f2;
	}

	/* #endif */
</style>

<style lang="scss" scoped>
	.order {
		width: 710rpx;
		background-color: #ffffff;
		margin: 20rpx auto;
		border: 1rpx solid $u-info-light;
		border-radius: 20rpx;
		box-sizing: border-box;
		padding: 40rpx;
		font-size: 28rpx;

		.top {
			display: flex;
			justify-content: space-between;

			.left {
				display: flex;
				align-items: center;

				.store {
					margin: 0 10rpx;
					font-size: 32rpx;
					font-weight: bold;
				}
			}

			.right {
				color: $u-warning-dark;
			}
		}

		.item {
			display: flex;
			margin: 20rpx 0 0;

			.left {
				margin-right: 20rpx;

				image {
					width: 200rpx;
					height: 200rpx;
					border-radius: 10rpx;
				}
			}

			.content {
				flex: 1;

				.title {
					font-size: 28rpx;
					line-height: 50rpx;
				}

				.type {
					margin: 10rpx 0;
					font-size: 24rpx;
					color: $u-tips-color;
				}

				.delivery-time {
					color: #e5d001;
					font-size: 24rpx;
				}
			}

			.right {
				margin-left: 10rpx;
				padding-top: 20rpx;
				text-align: right;

				.decimal {
					font-size: 24rpx;
					margin-top: 4rpx;
				}

				.number {
					color: $u-tips-color;
					font-size: 24rpx;
				}
			}
		}

		.total {
			margin-top: 20rpx;
			text-align: right;
			font-size: 24rpx;

			.total-price {
				font-size: 32rpx;
			}
		}

		.bottom {
			display: flex;
			margin-top: 40rpx;
			padding: 0 10rpx;
			justify-content: center;
			align-items: center;

			.btn {
				line-height: 52rpx;
				width: 160rpx;
				border-radius: 26rpx;
				border: 2rpx solid $u-border-color;
				font-size: 26rpx;
				text-align: center;
				color: $u-info-dark;
			}

			.evaluate {
				color: $u-warning-dark;
				border-color: $u-warning-dark;
			}
		}
	}

	.bground {
		border: 1rpx solid $u-info-light;
		border-radius: 40rpx;
		padding: 6rpx 20rpx;
	}
	
	.wrap {
		display: flex;
		flex-direction: column;
		height: calc(100vh - var(--window-top));
		width: 100%;
	}

	.swiper-box {
		flex: 1;
	}

	.swiper-item {
		height: 100%;
	}

	
	
	.btn-group {
		display: flex;
	}
	.btn-box {
		padding: 0 16rpx;
		width: 160rpx;
	}
</style>
